package com.cheval.rpcframe.protocal;

import com.cheval.rpcframe.common.Message;
import com.cheval.rpcframe.common.MessageType;
import com.cheval.rpcframe.handler.Handler;
import com.cheval.rpcframe.handler.HandlerContext;
import com.cheval.rpcframe.handler.RemoteInvokeHandler;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DispatcherServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(DispatcherServlet.class);

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletInputStream inputStream = req.getInputStream();
        ObjectInputStream ois = new ObjectInputStream(inputStream);
        try {
            Message message = (Message) ois.readObject();
            if (message == null) {
                logger.error("未读取到消息， 本次请求不处理");
                return;
            }
            Handler handler = null;
            if (message.getMessageType() == MessageType.INVOKE) {
                handler = new RemoteInvokeHandler();
            }
            HandlerContext handlerContext = new HandlerContext(handler, message.getInvocation());
            handlerContext.handle(resp);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
